﻿using log4net;
using MySql.Data.MySqlClient;
using Sunny.UI;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;

namespace FZRD
{
    public partial class Page7 : UIPage
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Page7));
        //监听线程
        [DisallowNull]
        public static Thread receiveThread3;

        private static bool isAlarmNotify = true;
        private static double axialForceExceeds = 10000.0;
        private static int repeatTimes = 100;

        private static bool isAlarmEmail = true;
        private static string alarmEmail = "";

        private static bool isAlarmPhone = true;
        private static string alarmPhone = "";

        private static string backupFilePath = "";

        private static string restoreFilePath = "";

        public static string connStr = "server=localhost;port=3306;database=fzrd;uid=root;pwd=123456;";

        public Page7()
        {
            InitializeComponent();

            isAlarmNotify = Convert.ToBoolean(ConfigurationManager.AppSettings["cbAlarmNotify"]);
            cbAlarmNotify.Checked = isAlarmNotify;

            axialForceExceeds = Convert.ToDouble(ConfigurationManager.AppSettings["tbAxialForceExceeds"]);
            tbAxialForceExceeds.Text = axialForceExceeds.ToString();

            repeatTimes = Convert.ToInt16(ConfigurationManager.AppSettings["tbRepeatTimes"]);
            tbRepeatTimes.Text = repeatTimes.ToString();

            isAlarmPhone = Convert.ToBoolean(ConfigurationManager.AppSettings["cbAlarmPhone"]);
            cbAlarmPhone.Checked = isAlarmPhone;

            tbAlarmPhone.Text = ConfigurationManager.AppSettings["tbAlarmPhone"];
            alarmPhone = tbAlarmPhone.Text;

            isAlarmEmail = Convert.ToBoolean(ConfigurationManager.AppSettings["cbAlarmEmail"]);
            cbAlarmEmail.Checked = isAlarmEmail;

            tbAlarmEmail.Text = ConfigurationManager.AppSettings["tbAlarmEmail"];
            alarmEmail = tbAlarmEmail.Text;

            tbBackupFilePath.Text = ConfigurationManager.AppSettings["tbBackupFilePath"];
            backupFilePath = tbBackupFilePath.Text;

            tbRestoreFilePath.Text = ConfigurationManager.AppSettings["tbRestoreFilePath"];
            restoreFilePath = tbRestoreFilePath.Text;

            //开启接收消息线程
            //receiveThread3 = new Thread(ReceiveMessage);
            //receiveThread3.Start();
        }

        //窗口关闭事件委托，在窗口关闭事件前处理
        private void Page6_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (receiveThread3 != null)
            {
                receiveThread3.Interrupt();
            }
        }

        public static bool getIsAlarmNotify()
        {
            return isAlarmNotify;
        }

        public static double getAxialForceExceeds()
        {
            return axialForceExceeds;
        }

        public static int getRepeatTimes()
        {
            return repeatTimes;
        }

        public static bool getIsAlarmPhone()
        {
            return isAlarmPhone;
        }

        public static string getAlarmPhone()
        {
            return alarmPhone;
        }

        public static bool getIsAlarmEmail()
        {
            return isAlarmEmail;
        }

        public static string getAlarmEmail()
        {
            return alarmEmail;
        }

        public static string getBackupFilePath()
        {
            return backupFilePath;
        }

        public static string getRestoreFilePath()
        {
            return restoreFilePath;
        }

        private void cbAlarmNotify_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                isAlarmNotify = this.cbAlarmNotify.Checked;
                this.tbAxialForceExceeds.Enabled = isAlarmNotify;
                this.tbRepeatTimes.Enabled = isAlarmNotify;
                this.cbAlarmEmail.Enabled = isAlarmNotify;
                this.tbAlarmEmail.Enabled = isAlarmNotify;
                this.cbAlarmPhone.Enabled = isAlarmNotify;
                this.tbAlarmPhone.Enabled = isAlarmNotify;

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                AppSettingsSection app = config.AppSettings;
                app.Settings["cbAlarmNotify"].Value = Convert.ToString(isAlarmNotify);
                config.Save(ConfigurationSaveMode.Modified);
                Page1.setIsAlarmNotify(isAlarmNotify);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void tbAxialForceExceeds_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if ((isAlarmNotify) && (this.tbAxialForceExceeds.Text.Length > 0))
                {
                    axialForceExceeds = Convert.ToDouble(this.tbAxialForceExceeds.Text);
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    AppSettingsSection app = config.AppSettings;
                    app.Settings["tbAxialForceExceeds"].Value = Convert.ToString(axialForceExceeds);
                    config.Save(ConfigurationSaveMode.Modified);
                    Page1.setAxialForceExceeds(axialForceExceeds);
                }
            }
            catch (Exception ex)
            {
                log.Error (ex.Message);
            }
        }

        private void tbRepeatTimes_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if ((isAlarmNotify) && (this.tbRepeatTimes.Text.Length > 0))
                {
                    repeatTimes = Convert.ToInt16(this.tbRepeatTimes.Text);
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    AppSettingsSection app = config.AppSettings;
                    app.Settings["tbRepeatTimes"].Value = Convert.ToString(repeatTimes);
                    config.Save(ConfigurationSaveMode.Modified);
                    Page1.setRepeatTimes(repeatTimes);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void tbAlarmPhone_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if ((this.cbAlarmPhone.Enabled) && (tbAlarmPhone.Text.Length > 0))
                {
                    alarmPhone = this.tbAlarmPhone.Text;
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    AppSettingsSection app = config.AppSettings;
                    app.Settings["tbAlarmPhone"].Value = tbAlarmPhone.Text;
                    config.Save(ConfigurationSaveMode.Modified);
                    Page1.setAlarmPhone(alarmPhone);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void cbAlarmEmail_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (isAlarmNotify)
                {
                    isAlarmEmail = this.cbAlarmEmail.Checked;
                    this.tbAlarmEmail.Enabled = isAlarmEmail;
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    AppSettingsSection app = config.AppSettings;
                    app.Settings["cbAlarmEmail"].Value = Convert.ToString(isAlarmEmail);
                    config.Save(ConfigurationSaveMode.Modified);
                    Page1.setIsAlarmEmail(isAlarmEmail);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void tbAlarmEmail_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if ((isAlarmNotify) && (isAlarmEmail) && (this.tbAlarmEmail.Text.Length > 0))
                {
                    alarmEmail = this.tbAlarmEmail.Text;
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    AppSettingsSection app = config.AppSettings;
                    app.Settings["tbAlarmEmail"].Value = alarmEmail;
                    config.Save(ConfigurationSaveMode.Modified);
                    Page1.setAlarmEmail(alarmEmail);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void cbAlarmPhone_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (isAlarmNotify)
                {
                    isAlarmPhone = this.cbAlarmPhone.Checked;
                    this.tbAlarmPhone.Enabled = isAlarmPhone;
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    AppSettingsSection app = config.AppSettings;
                    app.Settings["cbAlarmPhone"].Value = Convert.ToString(isAlarmPhone);
                    config.Save(ConfigurationSaveMode.Modified);
                    Page1.setIsAlarmPhone(isAlarmPhone);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void cbDailyTask_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbDailyTask.Checked)
                {
                    backupFilePath = tbBackupFilePath.Text;
                    DateTime dailyTaskTime = dtDailyTaskTime.Value;
                    QuartzTask.DailyTask(connStr, dailyTaskTime.Hour, dailyTaskTime.Minute);
                    RecordUserOperation("设置每日定时备份  日期：" + dailyTaskTime.Hour + ":" + dailyTaskTime.Minute + ":" + dailyTaskTime.Second);
                }
                else
                {
                    QuartzTask.CancelDailyTask();
                    RecordUserOperation("取消每日定时备份");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void cbWeeklyTask_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbWeeklyTask.Checked)
                {
                    backupFilePath = tbBackupFilePath.Text;
                    int day = cbWeeklyTaskDay.SelectedIndex;
                    if (day < 0 || day > 6)
                    {
                        MessageBox.Show("日期格式不对！（值：1 - 31）", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    DateTime weeklyTaskTime = dtWeeklyTaskTime.Value;
                    QuartzTask.WeeklyTask(connStr, day, weeklyTaskTime.Hour, weeklyTaskTime.Minute);
                    RecordUserOperation("设置每周定时备份  日期：" + day + " " + weeklyTaskTime.Hour + ":" + weeklyTaskTime.Minute + ":" + weeklyTaskTime.Second);
                }
                else
                {
                    QuartzTask.CancelWeeklyTask();
                    RecordUserOperation("取消每周定时备份");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void cbMonthlyTask_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbMonthlyTask.Checked)
                {
                    backupFilePath = tbBackupFilePath.Text;
                    string monthlyTaskDate = tbMonthlyTaskDate.Text;
                    int date = 1;
                    if (monthlyTaskDate != null && monthlyTaskDate.IsNullOrEmpty())
                    {
                        date = int.Parse(monthlyTaskDate);
                    }
                    if (date < 1 || date > 31)
                    {
                        MessageBox.Show("日期格式不对！（值：1 - 31）", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    DateTime monthlyTaskTime = dtMonthlyTaskTime.Value;
                    QuartzTask.MonthlyTask(connStr, date, monthlyTaskTime.Hour, monthlyTaskTime.Minute);
                    RecordUserOperation("设置每月定时备份  日期：" + monthlyTaskDate + " " + monthlyTaskTime.Hour + ":" + monthlyTaskTime.Minute + ":" + monthlyTaskTime.Second);
                }
                else
                {
                    QuartzTask.CancelMonthlyTask();
                    RecordUserOperation("取消每月定时备份");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void cbRestoreDatabaseButton_Click(object sender, EventArgs e)
        {
            try
            {
                QuartzTask.RestoreDatabase(connStr, restoreFilePath);
                RecordUserOperation("立即执行恢复备份到到数据库 备份文件：" + restoreFilePath);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void cbBackupDatabaseButton_Click(object sender, EventArgs e)
        {
            try
            {
                using (MySqlConnection mysqlConn = new MySqlConnection(connStr))
                {
                    mysqlConn.Open();
                    MySqlCommand mysqlCommand = new MySqlCommand();
                    mysqlCommand.Connection = mysqlConn;
                    // 创建备份实例
                    MySqlBackup mysqlBackup = new MySqlBackup(mysqlCommand);
                    string outpupFilePath = getBackupFilePath() + "fzrd-" + DateTime.Now.ToString("yyyyMMdd") + ".sql";
                    // 执行备份并保存到文件
                    mysqlBackup.ExportToFile(outpupFilePath);
                    log.Info("执行备份并保存到文件");
                    RecordUserOperation("立即执行备份并保存到文件：" + outpupFilePath);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }

        }

        private void uiBackupFilePathButton_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                folderBrowserDialog.ShowDialog();
                tbBackupFilePath.Text = folderBrowserDialog.SelectedPath; //获得选择的文件夹路径
                backupFilePath = tbBackupFilePath.Text;

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                AppSettingsSection app = config.AppSettings;
                app.Settings["tbBackupFilePath"].Value = backupFilePath;
                config.Save(ConfigurationSaveMode.Modified);
                RecordUserOperation("设置备份文件路径：" + backupFilePath);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        private void uiRestoreFilePathButton_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog openFileDialog = new OpenFileDialog())
                {
                    openFileDialog.InitialDirectory = tbRestoreFilePath.Text;
                    openFileDialog.Title = "Browse Files";
                    openFileDialog.Filter = "Text files (*.sql)|*.sql|All files (*.*)|*.*";
                    openFileDialog.FilterIndex = 2;
                    openFileDialog.RestoreDirectory = true;

                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        tbRestoreFilePath.Text = openFileDialog.FileName;
                        restoreFilePath = openFileDialog.FileName;

                        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        AppSettingsSection app = config.AppSettings;
                        app.Settings["tbRestoreFilePath"].Value = restoreFilePath;
                        config.Save(ConfigurationSaveMode.Modified);
                    }
                    RecordUserOperation("设置恢复文件路径：" + restoreFilePath);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        public void RecordUserOperation(string operation)
        {
            try
            {
                string userName = LoginForm.username;
                string userIp = "127.0.0.1";
                long recordTime = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeMilliseconds(); ;
                MainForm.db.ExecuteSql(
                    MainForm.db.Insert("system_operation_content")
                        .SetColumn("UserName", userName)
                        .SetColumn("UserIP", userIp)
                        .SetColumn("RecordTime", recordTime)
                        .SetColumn("Operation", operation)
                        .ToSql());
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

    }
}